/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var unUploadImages = 0;
var pdImages = [];
var pdId = false;

requirejs(['jquery', 'util', 'fancyBox', 'datatables', 'ztree', 'ztree_loader', 'ueditor', 'zxxFile'], function($, util, fancyBox, dataTables, ztree, treeLoader, ueditor) {
    $(function() {
        if ($('#mod').val() === 'edit') {
            // 编辑模式 存入图片列表
            $('.pd-images').each(function(i, node) {
                pdImages.push('product_hpic2__' + $(node).attr('data-imagepath'));
            });
            pdId = parseInt($('#pid').val());
        } else {
            pdId = false;
        }
        
        $('body').css('overflow-x', 'hidden');
        uep = UM.getEditor('ueditorp', {
            autoHeight: true
        });
        uep.ready(function() {
            uep.setWidth('100%');
            ueploaded = true;
        });
        // 图片已经上传过了。
        $('#save_product_btn').unbind('click').click(function() {
            // before check
            if (unUploadImages === 0) {
                __ProductAlterFinish();
            } else {
                $("#fileSubmit-pd")[0].click();
            }
        });

        var params = {
            fileInput: $("#fileImage-pd")[0],
            dragDrop: $("#fileDragArea-pd").get(0),
            upButton: $("#fileSubmit-pd").get(0),
            url: '?/vProduct/ImageUpload',
            filter: function(files) {
                var arrFiles = [];
                for (var i = 0, file; file = files[i]; i++) {
                    if (file.type.indexOf("image") === 0) {
                        if (file.size >= 512000) {
                            Alert('您这张"' + file.name + '"图片大小过大，应小于500k');
                        } else {
                            arrFiles.push(file);
                        }
                    } else {
                        Alert('文件"' + file.name + '"不是图片。');
                    }
                }
                return arrFiles;
            },
            onSelect: function(files, index) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    $('#pd-images-list').append('<img class="pd-images add" src="' + e.target.result + '" />');
                    // $('#appmsg_thumb-pd').hide();
                    // $('#appmsimg-preview-pd').attr('src', e.target.result).show();
                    // 未上传
                    unUploadImages++;
                };
                reader.readAsDataURL(files[index]);
            },
            onDelete: function(file) {
                ZXXFILEPD.funDeleteFile(file.index);
            },
            onDragOver: function() {
                $(this).addClass("upload_drag_hover");
            },
            onDragLeave: function() {
                $(this).removeClass("upload_drag_hover");
            },
            onProgress: function(file, loaded, total) {

            },
            onSuccess: function(file, response) {
                var res = response.toJson();
                pdImages.push('product_hpic2__' + res.imagename);
                if (--unUploadImages === 0) {
                    // 全部上传完毕
                    __ProductAlterFinish();
                }
            },
            onFailure: function(file) {

            },
            onComplete: function() {

            }
        };
        ZXXFILEPD = $.extend(ZXXFILE, params);
        ZXXFILEPD.init();
    });


    /**
     * 商品编辑结束
     * @returns {undefined}
     */
    function __ProductAlterFinish() {
        var title = $('#pd-form-title').val();
        var price = parseFloat($('#pd-form-prices').val());
        var discount = $('#pd-form-discount').val();
        var desc = uep.getContent();
        var subtitle = $('#pd-form-desc').val();
        var images = pdImages;

        // [HttpPost]
        $.post(shoproot + '?/WdminAjax/updateProduct', {
            product_id: !pdId ? 0 : pdId,
            product_name: title,
            product_prices: price > 0 ? price : 0,
            product_discount: discount,
            product_desc: desc,
            product_subtitle: subtitle,
            product_images: images,
            product_cat: $('#pd-form-cat').val()
        }, function(r) {
            if (r === '1') {
                pdImages.length = 0;
                ZXXFILE.fileFilter.length = 0;
                // __ProductEditFinish();
                util.Alert('保存成功');
            } else {
                util.Alert('保存失败');
            }
        });
    }

});